Page({
  data: {
    orders: [], // 订单列表
    filteredOrders: [], // 筛选后的订单列表
    searchValue: '', // 搜索框内容
    shareFileUrl: '', // 用于存储要分享的文件链接
    activeTab: 'unclaimedOrders', // 当前激活的 Tab，默认unclaimedOrders
    isLoading: false,
    orderIdByScan: '',
    activeOrders: [], // 非已完成
    completedOrders: [], // 已完成
    refundedOrders: [], // 已退款
    processFilterOptions: ['进行中','已完成','已退款'],
    selectedProcessFilterIndex: 0,
    expandedMap: {}, // 每个订单的展开状态
    userExpandedOrders: {}, // 用户手动展开的订单，这些订单不会被自动折叠
    showUrgentOnly: false, // 是否只显示急件
    unclaimedUrgentCount: 0, // 待领取订单中急件数量
    claimedUrgentCount: 0, // 我领取的订单中急件数量
    
    // 产品筛选相关数据
    productTypes: [], // 产品类型列表（从后端获取）
    selectedProductType: 'allOrders', // 当前选中的产品类型，默认"所有订单"
    selectedProductInfo: {}, // 当前选中产品的完整信息
    showProductDropdown: false, // 是否显示产品下拉菜单
    filteredProductTypes: [], // 过滤后的产品类型列表
    
    // 驿站筛选相关数据
    stationNames: [], // 从订单中提取的所有驿站名称（去重）
    selectedStationName: 'allStations', // 当前选中的驿站名称
    showStationFilter: false, // 是否显示驿站筛选（当选择代取快递时显示）
    showStationDropdown: false, // 是否显示驿站下拉菜单
    filteredStationNames: [], // 过滤后的驿站名称列表
  },

  // 状态顺序表
  STATUS_ORDER: [
    "待取货",  // 索引 0
    "待入库",  // 索引 1
    "待清洗",  // 索引 2
    "待送达",  // 索引 3
    "已完成"   // 索引 4
  ],

  // 页面显示时调用
  onLoad() {
    console.log('=== 页面加载开始 ===');
    console.log('当前activeTab:', this.data.activeTab);
    console.log('showUrgentOnly:', this.data.showUrgentOnly);
    this.fetchProductList(); // 先获取产品列表
    this.fetchOrders(); // 调用获取订单的函数
  },

  // 页面显示时调用
  onShow() {
    console.log('=== 页面显示 ===');
    console.log('当前activeTab:', this.data.activeTab);
    console.log('showUrgentOnly:', this.data.showUrgentOnly);
  },
  // 获取产品列表
  async fetchProductList() {
    try {
      console.log('========== fetchProductList 开始获取产品列表 ==========');
      
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolCode = selectedAddress?.addressCode;
      console.log('获取产品列表，学校代码:', schoolCode);
      
      const res = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          getProductListRequest: {
            schoolCode: schoolCode
          }
        }
      });

      console.log('获取产品列表响应:', res.result);

      if (res.result && res.result.code === 200) {
        const products = res.result.data.products || [];
        console.log('从云函数获取到的产品:', products);
        
        // 转换产品数据格式
        const productTypes = products.map(product => {
          console.log('处理产品:', product.productTitle, '产品ID:', product.productId);
          return {
            id: product.productId,
            name: product.productTitle,
            color: this.getProductColor(product.productId),
            desc: product.productDesc || ''
          };
        });

        // 添加"所有订单"选项
        productTypes.unshift({
          id: 'allOrders',
          name: '所有订单',
          color: '#795548',
          desc: '查看所有类型的订单'
        });

        this.setData({
          productTypes: productTypes,
          filteredProductTypes: productTypes
        });
        
        // 设置默认选中的产品信息
        const defaultProduct = productTypes.find(item => item.id === 'allOrders');
        this.setData({
          selectedProductInfo: defaultProduct || {}
        });
        
        console.log('产品列表设置成功:', productTypes);
      } else {
        console.error('获取产品列表失败:', res.result?.message || '未知错误');
        
        // 使用默认产品列表
        const defaultProductTypes = [
          { 
            id: 'PPacakgePickUp', 
            name: '快递代取', 
            color: '#4CAF50'
          },
          { 
            id: 'PWashShoes', 
            name: '洗鞋服务', 
            color: '#2196F3'
          },
          { 
            id: 'PWashClothes', 
            name: '洗衣服务', 
            color: '#FF9800'
          },
          { 
            id: 'PPaoTui', 
            name: '跑腿服务', 
            color: '#9C27B0'
          },
          { 
            id: 'PPrintBlackAndWhite', 
            name: '打印服务', 
            color: '#607D8B'
          },
          { 
            id: 'allOrders', 
            name: '所有订单', 
            color: '#795548'
          }
        ];
        
        this.setData({
          productTypes: defaultProductTypes,
          filteredProductTypes: defaultProductTypes,
          selectedProductInfo: defaultProductTypes.find(item => item.id === 'allOrders') || {}
        });
      }
    } catch (error) {
      console.error('获取产品列表失败:', error);
      
      // 使用默认产品列表
      const defaultProductTypes = [
        { 
          id: 'PPacakgePickUp', 
          name: '快递代取', 
          color: '#4CAF50'
        },
        { 
          id: 'PWashShoes', 
          name: '洗鞋服务', 
          color: '#2196F3'
        },
        { 
          id: 'PWashClothes', 
          name: '洗衣服务', 
          color: '#FF9800'
        },
        { 
          id: 'PPaoTui', 
          name: '跑腿服务', 
          color: '#9C27B0'
        },
        { 
          id: 'PPrintBlackAndWhite', 
          name: '打印服务', 
          color: '#607D8B'
        },
        { 
          id: 'allOrders', 
          name: '所有订单', 
          color: '#795548'
        }
      ];
      
      this.setData({
        productTypes: defaultProductTypes,
        filteredProductTypes: defaultProductTypes,
        selectedProductInfo: defaultProductTypes.find(item => item.id === 'allOrders') || {}
      });
    }
  },

  // 根据产品ID获取颜色
  getProductColor(productId) {
    const colorMap = {
      'PPacakgePickUp': '#4CAF50',
      'PWashShoes': '#2196F3',
      'PWashClothes': '#FF9800',
      'PPaoTui': '#9C27B0',
      'PPrintBlackAndWhite': '#607D8B'
    };
    return colorMap[productId] || '#4CAF50';
  },

  // 从订单数据中提取驿站名称
  extractStationNames() {
    console.log('========== extractStationNames 开始提取驿站名称 ==========');
    const stationSet = new Set();
    
    // 从所有订单中提取stationName
    this.data.orders.forEach(order => {
      if (order.orderItem.productId === 'PPacakgePickUp') {
        console.log('处理代取快递订单:', order.orderId);
        
        // 从pickupInputs中提取
        if (order.pickupInputs && order.pickupInputs.length > 0) {
          order.pickupInputs.forEach(pickup => {
            if (pickup.stationName) {
              console.log('从pickupInputs提取驿站名称:', pickup.stationName);
              stationSet.add(pickup.stationName);
            }
          });
        }
        
        // 从packagePickupInfos中提取（兼容不同数据结构）
        if (order.packagePickupInfos && order.packagePickupInfos.length > 0) {
          order.packagePickupInfos.forEach(pickup => {
            if (pickup.pickupAddress) {
              console.log('从packagePickupInfos提取驿站名称:', pickup.pickupAddress);
              stationSet.add(pickup.pickupAddress);
            }
          });
        }
      }
    });
    
    const stationNames = Array.from(stationSet);
    stationNames.unshift('allStations'); // 添加"所有驿站"选项
    
    console.log('提取到的驿站名称列表:', stationNames);
    
    this.setData({
      stationNames: stationNames,
      filteredStationNames: stationNames
    });
    
    return stationNames;
  },

  // 更新驿站名称列表
  updateStationNames() {
    console.log('========== updateStationNames 更新驿站名称 ==========');
    const stationNames = this.extractStationNames();
    
    // 如果当前选中的驿站不在新的列表中，重置为"所有驿站"
    if (stationNames.length > 0 && !stationNames.includes(this.data.selectedStationName)) {
      this.setData({
        selectedStationName: 'allStations'
      });
    }
    
    return stationNames;
  },

  getOrderTypeByProductId(order) {
    let productId = order.orderItem.productId;
    if (productId == 'PWashShoes') {
      return '洗鞋'
    }
    else if (productId == 'PPacakgePickUp') {
      return '代取'
    }
    else if (productId == 'PWashClothes') {
      return '洗衣'
    }
    else if (productId == 'PPrintBlackAndWhite') {
      return '打印'
    }
    else if (productId == 'PPaoTui') {
      return '跑腿'
    }
    return "-"
  },
  // 判断订单是否包含急件
  isUrgentOrder(order) {
    // 检查是否为代取快递订单
    if (order.orderItem && order.orderItem.productId === 'PPacakgePickUp') {
      // 检查快递信息中是否有急件
      if (order.packagePickupInfos && order.packagePickupInfos.length > 0) {
        const isUrgent = order.packagePickupInfos.some(pkg => pkg.pickupSize === '急件');
        if (isUrgent) {
          console.log('发现急件订单:', order.orderId, order.packagePickupInfos);
        }
        return isUrgent;
      }
    }
    return false;
  },
  // 提取订单价格（单位元），优先 payAmount/totalAmount，其次 orderItem.price
  getOrderPriceText(order) {
    const toYuanStr = (v) => {
      if (v === null || v === undefined) return '';
      const n = Number(v);
      if (Number.isNaN(n)) return '';
      return `¥${n.toFixed(2)}`;
    };
    if (order.payAmount !== undefined) return toYuanStr(order.payAmount);
    if (order.totalAmount !== undefined) return toYuanStr(order.totalAmount);
    if (order.orderItem && order.orderItem.price !== undefined) return toYuanStr(order.orderItem.price);
    return '';
  },
  // 获取订单信息
  async fetchOrders() {
    if (this.data.isLoading) return; // 如果正在加载，避免重复请求
    this.setData({ isLoading: true }); // 设置加载状态

    try {
      // 从缓存获取选中的学校代码
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolCode = selectedAddress && selectedAddress.addressCode ? selectedAddress.addressCode : null;

      // 构建基础请求参数
      const baseRequestParams = {
        page: this.data.page, // 当前页码
        pageSize: this.data.pageSize, // 每页条数
        schoolCode: schoolCode,
        excludeRefundedOrders: true, // 列表查询时排除退款订单
        // 添加产品类型筛选
        orderType: this.data.selectedProductType === 'allOrders' ? null : this.data.selectedProductType
      };

      // 调用云函数获取订单信息
      let res;
      if(this.data.activeTab === "unclaimedOrders"){
        res = await wx.cloud.callFunction({
          name: "xiaoBangCommonFunction", // 云函数名称
          data: {
            getOrderListForManageRequest: {
              ...baseRequestParams,
              noRiderId: true
            }
          },
        });
      }else {
        res = await wx.cloud.callFunction({
          name: "xiaoBangCommonFunction", // 云函数名称
          data: {
            getOrderListForManageRequest: {
              ...baseRequestParams,
              riderId: wx.getStorageSync('openId')
            }
          },
        });
      }
      
      if (res.result.code === 200) {
        let { orders, total } = res.result.data;
        console.log("orders", orders)
        console.log("total", total)
        orders.forEach(order => {
          order.orderType = this.getOrderTypeByProductId(order);
          order.priceText = this.getOrderPriceText(order);
          // 跑腿服务多地址时间信息字段映射
          order.paoTuiPickupAddress = order.pao_tui_pickup_address;
          order.paoTuiPickupTime = order.pao_tui_pickup_time;
          order.paoTuiDeliveryAddress = order.pao_tui_delivery_address;
          order.paoTuiDeliveryTime = order.pao_tui_delivery_time;
          order.paoTuiNote = order.paoTuiNote;
          // 为每个订单添加急件标识
          order.hasUrgentPackage = this.isUrgentOrder(order);
        })
        // 计算急件数量
        const allOrders = this.data.page === 1 ? orders : [...this.data.orders, ...orders];
        const unclaimedUrgentCount = allOrders.filter(order => 
          !order.deliverOutUserId && this.isUrgentOrder(order)
        ).length;
        const claimedUrgentCount = allOrders.filter(order => 
          order.deliverOutUserId && this.isUrgentOrder(order)
        ).length;

        // 更新页面数据
        this.setData({
          orders: allOrders, // 如果是第一页，覆盖数据；否则追加数据
          total,
          unclaimedUrgentCount,
          claimedUrgentCount,
        }, () => {
          // 如果是代取快递产品，提取驿站名称
          if (this.data.selectedProductType === 'PPacakgePickUp') {
            this.updateStationNames();
          }
          
          this.updateFilteredOrders();
        });
        console.log("data orders", orders)
      } else {
        wx.showToast({
          title: res.result.message || "获取订单失败",
          icon: "none",
        });
      }
    } catch (error) {
      console.error("调用云函数失败：", error);
      wx.showToast({
        title: "获取订单失败，请稍后重试",
        icon: "none",
      });
    } finally {
      this.setData({ isLoading: false }); // 重置加载状态
    }
  },

  // 输入框事件
  onInput(e) {
    this.setData({ searchValue: e.detail.value });
  },

  // 扫码获取订单号并查询订单
  scanCode() {
    wx.scanCode({
      onlyFromCamera: true, // 限制只能通过摄像头扫描
      scanType: ['barCode', 'qrCode'], // 支持条形码和二维码
      success: async (res) => {
        try {
          // console.log('扫描结果:', res.result);
          const orderId = res.result.trim(); // 假设扫码结果直接返回订单号
          // console.log('解析出的订单号:', orderId);
          this.setData({
            orderIdByScan:orderId
          })
          await this.fetchOrdersOrFetchScanOrder();
        } catch (err) {
          // console.error('解析条形码内容失败或查询订单失败:', err);
          wx.showToast({
            title: '订单查询失败，请稍后重试',
            icon: 'none',
          });
  
          // 清空当前订单列表
          this.setData({
            orders: [], // 清空订单数据，页面不显示任何内容
          });
        }
      },
      fail: (err) => {
        // console.error('扫描条形码失败:', err);
        wx.showToast({
          title: '扫码失败',
          icon: 'none',
        });
  
        // 清空当前订单列表
        this.setData({
          orders: [], // 清空订单数据，页面不显示任何内容
        });
      },
    });
  },

  // 根据输入框内容查询订单
  searchOrder() {
    const { searchValue } = this.data;
  
    // 判断输入是否为空
    if (!searchValue.trim()) {
      // 重置为默认列表
      this.setData({
        orders: [],
        page: 1,
        orderIdByScan: '',
      }, () => {
        this.fetchOrdersOrFetchScanOrder();
      });
      return;
    }
  
    // 从缓存获取选中的学校代码
    const selectedAddress = wx.getStorageSync('selectedAddress');
    const schoolCode = selectedAddress && selectedAddress.addressCode ? selectedAddress.addressCode : null;

    // 调用云函数查询订单
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction', // 云函数名称
      data: {
        getOrderListForManageRequest: {
          orderId: searchValue.trim(), // 传入订单号
          schoolCode: schoolCode,
          excludeRefundedOrders: false // 搜索时允许查询退款订单
        }
      },
    }).then((res) => {
        console.log('云函数返回结果:', res);
  
        // 判断云函数返回是否成功
        if (res.result.code === 200) {
          const { orders } = res.result.data;
          console.log('查询到的订单信息:', orders);
  
          // 更新页面数据，覆盖当前订单列表
          this.setData({
            orders: (orders || []).map(o => ({
              ...o,
              orderType: this.getOrderTypeByProductId(o),
              priceText: this.getOrderPriceText(o),
              hasUrgentPackage: this.isUrgentOrder(o),
            })),
          }, () => {
            this.updateFilteredOrders();
          });
        } else {
          console.error('未找到订单:', res.result.message || '无相关数据');
          wx.showToast({
            title: res.result.message || '未找到订单',
            icon: 'none',
          });
  
          // 清空当前订单列表
          this.setData({
            orders: [], // 清空订单数据，页面不显示任何内容
          }, () => {
            this.updateFilteredOrders();
          });
        }
      })
      .catch((err) => {
        console.error('查询订单失败:', err);
        wx.showToast({
          title: '订单查询失败，请稍后重试',
          icon: 'none',
        });
  
        // 清空当前订单列表
        this.setData({
          orders: [], // 清空订单数据，页面不显示任何内容
        }, () => {
          this.updateFilteredOrders();
        });
      });
  },

  // 照片上传逻辑（支持多张上传，最多 3 张）
  async uploadPhotoBeforeCleaningPhotos(e) {
    console.log("e:",e)
    const { id: orderId} = e.currentTarget.dataset; // 获取订单 ID 和照片类型
    const orderIndex = this.data.orders.findIndex(order => order.orderId === orderId);

    if (orderIndex === -1) {
      wx.showToast({
        title: '订单信息未找到',
        icon: 'none',
      });
      return;
    }

    const currentPhotos = this.data.orders[orderIndex].beforeCleaningPhotos

    if (currentPhotos.length >= 3) {
      wx.showToast({
        title: '最多可上传 3 张照片',
        icon: 'none',
      });
      return;
    }

    try {
      const { tempFilePaths } = await wx.chooseImage({
        count: 3 - currentPhotos.length, // 允许上传的剩余照片数量
        sizeType: ['compressed'], // 压缩图片
        sourceType: ['album', 'camera'], // 可以从相册或相机选择
      });

      const uploadPromises = tempFilePaths.map((filePath, index) => {
        const cloudPath = `order-photos/${orderId}-${Date.now()}-${index}.jpg`;
        return wx.cloud.uploadFile({
          cloudPath,
          filePath,
        });
      });

      const uploadResults = await Promise.all(uploadPromises);
      const uploadedFilePaths = uploadResults.map(res => res.fileID); // 获取上传成功的文件路径

      const updateData = {};
      updateData.beforeCleaningPhotos = uploadedFilePaths;

      const cloudFunctionRes = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          updateOrderStatusRequest: {
            orderId,
            ...updateData,
          }
        },
      });

      if (cloudFunctionRes.result.code === 200) {
        const updatedOrders = [...this.data.orders];
        updatedOrders[orderIndex].beforeCleaningPhotos = [
          ...(currentPhotos || []),
          ...uploadedFilePaths,
        ];

        this.setData({ orders: updatedOrders }, () => {
          this.updateFilteredOrders();
        });

        wx.showToast({
          title: '照片上传成功',
          icon: 'success',
        });
      } else {
        wx.showToast({
          title: cloudFunctionRes.result.message || '照片上传失败',
          icon: 'none',
        });
      }
    } catch (err) {
      console.error('上传照片失败:', err);
      wx.showToast({
        title: '照片上传失败，请重试',
        icon: 'none',
      });
    }
  },

  async uploadPhotoAfterCleaningPhotos(e) {
    console.log("e:",e)
    const { id: orderId} = e.currentTarget.dataset; // 获取订单 ID 和照片类型
    const orderIndex = this.data.orders.findIndex(order => order.orderId === orderId);

    if (orderIndex === -1) {
      wx.showToast({
        title: '订单信息未找到',
        icon: 'none',
      });
      return;
    }

    const currentPhotos = this.data.orders[orderIndex].afterCleaningPhotos

    if (currentPhotos.length >= 3) {
      wx.showToast({
        title: '最多可上传 3 张照片',
        icon: 'none',
      });
      return;
    }

    try {
      const { tempFilePaths } = await wx.chooseImage({
        count: 3 - currentPhotos.length, // 允许上传的剩余照片数量
        sizeType: ['compressed'], // 压缩图片
        sourceType: ['album', 'camera'], // 可以从相册或相机选择
      });

      const uploadPromises = tempFilePaths.map((filePath, index) => {
        const cloudPath = `order-photos/${orderId}-${Date.now()}-${index}.jpg`;
        return wx.cloud.uploadFile({
          cloudPath,
          filePath,
        });
      });

      const uploadResults = await Promise.all(uploadPromises);
      const uploadedFilePaths = uploadResults.map(res => res.fileID); // 获取上传成功的文件路径

      const updateData = {};
      updateData.afterCleaningPhotos = uploadedFilePaths;

      const cloudFunctionRes = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          updateOrderStatusRequest: {
            orderId,
            ...updateData,
          }
        },
      });

      if (cloudFunctionRes.result.code === 200) {
        const updatedOrders = [...this.data.orders];
        updatedOrders[orderIndex].afterCleaningPhotos = [
          ...(currentPhotos || []),
          ...uploadedFilePaths,
        ];

        this.setData({ orders: updatedOrders }, () => {
          this.updateFilteredOrders();
        });

        wx.showToast({
          title: '照片上传成功',
          icon: 'success',
        });
      } else {
        wx.showToast({
          title: cloudFunctionRes.result.message || '照片上传失败',
          icon: 'none',
        });
      }
    } catch (err) {
      console.error('上传照片失败:', err);
      wx.showToast({
        title: '照片上传失败，请重试',
        icon: 'none',
      });
    }
  },

  async uploadPhotoAfterDelivered(e) {
    console.log("e:",e)
    const { id: orderId} = e.currentTarget.dataset; // 获取订单 ID 和照片类型
    const orderIndex = this.data.orders.findIndex(order => order.orderId === orderId);

    if (orderIndex === -1) {
      wx.showToast({
        title: '订单信息未找到',
        icon: 'none',
      });
      return;
    }

    const currentPhotos = this.data.orders[orderIndex].deliveredPhotos || [];

    if (currentPhotos.length >= 3) {
      wx.showToast({
        title: '最多可上传 3 张照片',
        icon: 'none',
      });
      return;
    }

    try {
      const { tempFilePaths } = await wx.chooseImage({
        count: 3 - currentPhotos.length, // 允许上传的剩余照片数量
        sizeType: ['compressed'], // 压缩图片
        sourceType: ['album', 'camera'], // 可以从相册或相机选择
      });

      const uploadPromises = tempFilePaths.map((filePath, index) => {
        const cloudPath = `order-photos/${orderId}-${Date.now()}-${index}.jpg`;
        return wx.cloud.uploadFile({
          cloudPath,
          filePath,
        });
      });

      const uploadResults = await Promise.all(uploadPromises);
      const uploadedFilePaths = uploadResults.map(res => res.fileID); // 获取上传成功的文件路径

      const updateData = {};
      updateData.deliveredPhotos = uploadedFilePaths;

      const cloudFunctionRes = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          updateOrderStatusRequest: {
            orderId,
            ...updateData,
          }
        },
      });

      if (cloudFunctionRes.result.code === 200) {
        const updatedOrders = [...this.data.orders];
        updatedOrders[orderIndex].deliveredPhotos = [
          ...(currentPhotos || []),
          ...uploadedFilePaths,
        ];

        this.setData({ orders: updatedOrders }, () => {
          this.updateFilteredOrders();
        });

        wx.showToast({
          title: '照片上传成功',
          icon: 'success',
        });
      } else {
        wx.showToast({
          title: cloudFunctionRes.result.message || '照片上传失败',
          icon: 'none',
        });
      }
    } catch (err) {
      console.error('上传照片失败:', err);
      wx.showToast({
        title: '照片上传失败，请重试',
        icon: 'none',
      });
    }
  },

  // 打印订单
  printOrder1(e) {
    const { id } = e.currentTarget.dataset; // 获取订单 ID
    this.print(id, 1);
  },

  downloadFile(e) {
    const fileUrl = e.currentTarget.dataset.id; // 获取文件 URL
    if (!fileUrl) {
      wx.showToast({
        title: '文件地址无效',
        icon: 'none',
      });
      return;
    }
  
    wx.showLoading({
      title: '下载中...',
    });
  
    wx.downloadFile({
      url: fileUrl, // 文件地址
      success: (res) => {
        if (res.statusCode === 200) {
          // 下载成功，保存到本地
          wx.saveFile({
            tempFilePath: res.tempFilePath, // 临时文件路径
            success: (saveRes) => {
              wx.hideLoading();
              wx.showToast({
                title: '下载成功',
                icon: 'success',
              });
              console.log('文件已保存到本地路径：', saveRes.savedFilePath);
            },
            fail: (err) => {
              wx.hideLoading();
              wx.showToast({
                title: '保存失败',
                icon: 'none',
              });
              console.error('保存失败：', err);
            },
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '下载失败，请重试',
            icon: 'none',
          });
          console.error('下载失败，状态码：', res.statusCode);
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({
          title: '下载失败，请检查网络',
          icon: 'none',
        });
        console.error('下载文件失败：', err);
      },
    });
  },

  // 按钮点击事件
  copyFileUrl(e) {
    const orderInfo = e.currentTarget.dataset.order; // 获取按钮传递的文件 URL
    let copyText = "";
    console.log("copyFileUrl",JSON.stringify(orderInfo));
    copyText = copyText +  orderInfo.printInfo.fileUrl + "\n";
    copyText = copyText + "订单号: "+ orderInfo.orderId + "\n"
    console.log("copyFileUrl",JSON.stringify(copyText));
    // 将 copyText 拷贝到剪切板 -
    wx.setClipboardData({
      data: copyText,
      success: () => {
          wx.showToast({
              title: '复制成功',
              icon: 'success',
              duration: 2000
          });
      },
      fail: (err) => {
          console.error("复制到剪切板失败：", err);
          wx.showToast({
              title: '复制失败',
              icon: 'none',
              duration: 2000
          });
      }
  });
  },

  printOrder2(e) {
    const { id } = e.currentTarget.dataset; // 获取订单 ID
    this.print(id, 2);
  },
  
  printOrder3(e) {
    const { id } = e.currentTarget.dataset; // 获取订单 ID
    this.print(id, 3);
  },

  print(orderId, times){
    // 调用云函数进行打印
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction', // 云函数名称
      data: {
        "printTicketRequest":{
          orderId: orderId, // 将订单信息传递给云函数
          times: times
        }
      },
      success: (res) => {
        console.log('云函数调用成功:', res);
        
        const data = res.result;
        if (data.ret === 0) {
          wx.showToast({
            title: '打印成功',
            icon: 'success',
          });
        } else {
          wx.showToast({
            title: `打印失败: ${data.msg}`,
            icon: 'none',
          });
        }
      },
      fail: (err) => {
        console.error('云函数调用失败:', err);
        wx.showToast({
          title: '打印失败，请检查网络',
          icon: 'none',
        });
      },
    });
  },

// 通用状态流转处理
async handleStatusUpdate(order, targetStatus) {
  const currentStatus = order.processStatus; // 当前订单状态
  const currentIndex = this.STATUS_ORDER.indexOf(currentStatus); // 当前状态索引
  const targetIndex = this.STATUS_ORDER.indexOf(targetStatus); // 目标状态索引

  if (currentIndex === -1 || targetIndex === -1) {
    wx.showToast({
      title: '状态流转无效',
      icon: 'none',
    });
    return;
  }

  if (targetIndex === currentIndex + 1) {
    // 相邻状态，直接流转
    this.updateOrderStatus(order.orderId, targetStatus, "状态流转成功");
  } else if (targetIndex < currentIndex) {
    // 逆转状态，不允许
    wx.showToast({
      title: '不允许逆转状态',
      icon: 'none',
    });
  } else {
    // 非相邻状态，提示跳跃状态流转
    wx.showModal({
      title: "状态跳跃确认",
      content: `当前状态为: ${currentStatus}，目标状态为: ${targetStatus}，是否确认跳跃？`,
      success: (res) => {
        if (res.confirm) {
          this.updateOrderStatus(order.orderId, targetStatus, "状态跳跃成功");
        }
      },
    });
  }
},

// 更新订单状态
updateOrderStatus(orderId, processStatus, successMessage) {
  wx.cloud.callFunction({
    name: "xiaoBangCommonFunction", // 云函数名称
    data: {
      updateOrderStatusRequest: {
        orderId,
        processStatus,
      }
    },
    success: (res) => {
      if (res.result.code === 200) {
        const updatedOrders = this.data.orders.map((item) => {
          if (item.orderId === orderId) {
            return {
              ...item,
              processStatus, // 更新状态
            };
          }
          return item;
        });

        this.setData({ orders: updatedOrders }); // 更新页面数据
        wx.showToast({ title: successMessage, icon: "success" });
      } else {
        wx.showToast({
          title: res.result.message || "状态更新失败",
          icon: "none",
        });
      }
    },
    fail: (err) => {
      console.error("更新订单状态失败:", err);
      wx.showToast({ title: "网络错误，状态更新失败", icon: "none" });
    },
  });
},

getTargetStatusWhenClaimByRider(order) {
  let targetStatus = '';
    const productId = order.orderItem.productId;
    if (productId === 'PPrintBlackAndWhite') {
      targetStatus = '';
    }
    else if (productId === 'PPacakgePickUp') {
      targetStatus = '待送达';
    }
    else if (productId === 'PWashShoes'||productId === 'PWashClothes') {
      targetStatus = '待入库';
    }
    else if (productId === 'PPaoTui') {
      targetStatus = '处理中';
    }
    return targetStatus;
},
async fetchOrdersOrFetchScanOrder() {
  if (this.data.orderIdByScan) {
    console.log('fetchOrdersOrFetchScanOrder.orderId:', this.data.orderIdByScan);
      // 从缓存获取选中的学校代码
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolCode = selectedAddress && selectedAddress.addressCode ? selectedAddress.addressCode : null;

      // 调用云函数根据订单号查询订单信息
      const cloudRes = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction', // 云函数名称
        data: {
          getOrderListForManageRequest: {
            orderId: this.data.orderIdByScan, // 传入订单号
            schoolCode: schoolCode,
            excludeRefundedOrders: false // 扫码时允许查询退款订单
          }
        },
      });

    

    // 判断云函数返回是否成功
    if (cloudRes.result.code === 200) {
      const { orders } = cloudRes.result.data;
      // console.log('扫码获取的订单信息:', orders);

      orders.forEach(order => {
        order.orderType = this.getOrderTypeByProductId(order);
        order.priceText = this.getOrderPriceText(order);
        // 跑腿服务多地址时间信息字段映射
        order.paoTuiPickupAddress = order.pao_tui_pickup_address;
        order.paoTuiPickupTime = order.pao_tui_pickup_time;
        order.paoTuiDeliveryAddress = order.pao_tui_delivery_address;
        order.paoTuiDeliveryTime = order.pao_tui_delivery_time;
        order.paoTuiNote = order.paoTuiNote;
        // 为每个订单添加急件标识
        order.hasUrgentPackage = this.isUrgentOrder(order);
      })
      
      // 更新页面数据，覆盖当前订单列表
      this.setData({
        orders: orders || [], // 如果云函数返回为空，设置为空数组
      }, () => {
        this.updateFilteredOrders();
      });
    } else {
      // console.error('未找到订单:', cloudRes.result.message || '无相关数据');
      wx.showToast({
        title: cloudRes.result.message || '未找到订单',
        icon: 'none',
      });

      // 清空当前订单列表
      this.setData({
        orders: [], // 清空订单数据，页面不显示任何内容
      }, () => {
        this.updateFilteredOrders();
      });
    }
  } else {
    this.fetchOrders();
  }
},
// 领取订单
claimOrder(e) {
  const riderUserId = wx.getStorageSync('openId');
  const { id } = e.currentTarget.dataset; // 获取订单 ID
  const order = this.data.orders.find((item) => item.orderId === id);

  if (!order) {
    wx.showToast({ title: "订单信息未找到", icon: "none" });
    return;
  }
  let targetStatus = this.getTargetStatusWhenClaimByRider(order);
  wx.cloud.callFunction({
    name: "xiaoBangCommonFunction",
    data: {
      updateOrderStatusRequest: {
        orderId: id,
        processStatus: targetStatus, // 更新状态
        riderUserId, // 绑定骑手 ID
      }
    },
    success: (res) => {
      if (res.result.code === 200) {
        this.fetchOrdersOrFetchScanOrder();
        wx.showToast({ title: "订单领取成功", icon: "success" });
      } else {
        wx.showToast({
          title: res.result.message || "订单领取失败",
          icon: "none",
        });
      }
    },
    fail: (err) => {
      console.error("订单领取失败:", err);
      wx.showToast({ title: "网络错误，订单领取失败", icon: "none" });
    },
  });
},

confirmArrival(e) {
  const { id } = e.currentTarget.dataset; // 获取订单 ID
  const order = this.data.orders.find((item) => item.orderId === id);

  if (!order) {
    wx.showToast({ title: "订单信息未找到", icon: "none" });
    return;
  }
  if(!order.deliveredPhotos) {
    wx.showToast({ title: "请先上传送达照片", icon: "none" });
    return;
  }

  // 更新状态为"已完成"
  this.updateOrderStatus(id, "已完成", "订单已完成");
  this.fetchOrdersOrFetchScanOrder();
},

// 点击预览图片
 previewImage(e) {
  const current = e.currentTarget.dataset.src; // 当前点击图片的地址
  const packageIndex = e.currentTarget.dataset.packageIndex;
  const photoIndex = e.currentTarget.dataset.photoIndex;
  const orderIndex = e.currentTarget.dataset.orderIndex;
  
  console.log("riderOperation.previewImage.current", current);
  console.log("riderOperation.previewImage.orderIndex", orderIndex);
  console.log("riderOperation.previewImage.packageIndex", packageIndex);
  
  let urls = [];
  
  // 如果是包裹图片预览
  if (packageIndex !== undefined && photoIndex !== undefined && orderIndex !== undefined) {
    // 根据当前标签页选择正确的数据源
    let targetOrders = [];
    if (this.data.activeTab === 'myOrders') {
      // 在我领取的订单页面，使用activeOrders或completedOrders
      targetOrders = [...this.data.activeOrders, ...this.data.completedOrders];
    } else {
      // 在其他页面，使用orders
      targetOrders = this.data.orders;
    }
    
    // 使用传入的订单索引从正确的数据源中获取订单
    const order = targetOrders[orderIndex];
    if (order && order.packagePickupInfos && order.packagePickupInfos[packageIndex] && order.packagePickupInfos[packageIndex].photos) {
      urls = order.packagePickupInfos[packageIndex].photos;
    }
  } else {
    // 其他图片预览（保持原有逻辑）
    urls = [current];
  }
  
  wx.previewImage({
    current: current, // 当前显示图片的 HTTP 链接
    urls: urls // 需要预览的图片 HTTP 链接列表
  });
 },

 // 切换产品类型下拉菜单
  toggleProductDropdown() {
    this.setData({
      showProductDropdown: !this.data.showProductDropdown
    });
  },

  // 选择产品类型
  selectProductType(e) {
    const productType = e.currentTarget.dataset.type;
    console.log('========== selectProductType 被调用 ==========');
    console.log('选择的产品类型:', productType);
    
    const selectedProduct = this.data.productTypes.find(item => item.id === productType);
    
    this.setData({
      selectedProductType: productType,
      selectedProductInfo: selectedProduct || {},
      showProductDropdown: false,
      showStationFilter: productType === 'PPacakgePickUp', // 只有代取快递时显示驿站筛选
      page: 1,
      orders: []
    });
    
    // 如果是代取快递，提取驿站名称
    if (productType === 'PPacakgePickUp') {
      this.updateStationNames();
    }
    
    console.log('产品类型选择完成，准备重新加载订单');
    this.fetchOrders();
  },

  // 切换驿站下拉菜单
  toggleStationDropdown() {
    this.setData({
      showStationDropdown: !this.data.showStationDropdown
    });
  },

  // 选择驿站名称
  selectStationName(e) {
    const stationName = e.currentTarget.dataset.station;
    console.log('========== selectStationName 被调用 ==========');
    console.log('选择的驿站名称:', stationName);
    
    this.setData({
      selectedStationName: stationName,
      showStationDropdown: false
    });
    
    // 重新筛选订单
    this.filterOrdersByProductAndStation();
  },

  // 组合筛选逻辑（产品类型 + 驿站名称）
  filterOrdersByProductAndStation() {
    console.log('========== filterOrdersByProductAndStation 组合筛选 ==========');
    console.log('当前产品类型:', this.data.selectedProductType);
    console.log('当前驿站名称:', this.data.selectedStationName);
    
    let filtered = [...this.data.orders];
    
    // 产品筛选
    if (this.data.selectedProductType !== 'allOrders') {
      filtered = filtered.filter(order => 
        order.orderItem.productId === this.data.selectedProductType
      );
      console.log('产品筛选后订单数量:', filtered.length);
    }
    
    // 驿站筛选（仅对代取快递生效）
    if (this.data.selectedProductType === 'PPacakgePickUp' && 
        this.data.selectedStationName !== 'allStations') {
      filtered = filtered.filter(order => {
        // 检查pickupInputs
        if (order.pickupInputs && order.pickupInputs.length > 0) {
          return order.pickupInputs.some(pickup => 
            pickup.stationName === this.data.selectedStationName
          );
        }
        
        // 检查packagePickupInfos
        if (order.packagePickupInfos && order.packagePickupInfos.length > 0) {
          return order.packagePickupInfos.some(pickup => 
            pickup.pickupAddress === this.data.selectedStationName
          );
        }
        
        return false;
      });
      console.log('驿站筛选后订单数量:', filtered.length);
    }
    
    // 更新筛选结果
    this.updateFilteredOrders(filtered);
  },

 // 切换 Tab 
  switchTab(e) {
    const { tab } = e.currentTarget.dataset;
    console.log('切换标签页到:', tab);
    console.log('当前activeTab:', this.data.activeTab);

    // 更新 activeTab 并清空当前订单列表，再重新获取数据
    this.setData({ 
      activeTab: tab, 
      orders: [], // 清空当前订单数据，以便显示新的数据
      page: 1, // 重置页码
      orderIdByScan:'',
      selectedProcessFilterIndex: 0,
      showUrgentOnly: false, // 切换标签页时重置急件过滤状态
    }, () => {
      console.log('标签页切换完成，当前activeTab:', this.data.activeTab);
      console.log('activeTab === myOrders:', this.data.activeTab === 'myOrders');
      console.log('activeTab === unclaimedOrders:', this.data.activeTab === 'unclaimedOrders');
      this.updateFilteredOrders();
      this.fetchOrdersOrFetchScanOrder(); // 调用 fetchOrders 获取对应 Tab 的数据
    });
},

// 一键拨打电话
callPhone(e) {
  const phone = e.currentTarget.dataset.phone;
  if (!phone) {
    wx.showToast({ title: '无效的电话号码', icon: 'none' });
    return;
  }
  wx.makePhoneCall({
    phoneNumber: phone
  });
},

  // 处理状态筛选变化（进行中/已完成）
  onProcessFilterChange(e) {
    const index = e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.index !== undefined
      ? Number(e.currentTarget.dataset.index)
      : (e.detail && e.detail.value ? Number(e.detail.value) : 0);
    
    let orderStatus;
    if (index === 0) {
      // 进行中
      orderStatus = 'inProgress';
    } else if (index === 1) {
      // 已完成
      orderStatus = 'done';
    } else if (index === 2) {
      // 已退款
      orderStatus = 'refunded';
    }
    
    this.setData({ selectedProcessFilterIndex: index }, () => {
      // 调用后端接口获取筛选后的数据
      this.fetchOrdersWithOrderStatus(orderStatus);
    });
  },

  // 根据订单状态获取订单列表
  async fetchOrdersWithOrderStatus(orderStatus) {
    if (this.data.isLoading) return; // 如果正在加载，避免重复请求
    this.setData({ isLoading: true }); // 设置加载状态

    try {
      // 从缓存获取选中的学校代码
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolCode = selectedAddress && selectedAddress.addressCode ? selectedAddress.addressCode : null;

      // 构建请求参数
      const requestParams = {
        page: 1, // 重置页码
        pageSize: this.data.pageSize,
        schoolCode: schoolCode,
        excludeRefundedOrders: orderStatus !== 'refunded', // 只有查询已退款时才不排除
        // 添加产品类型筛选
        orderType: this.data.selectedProductType === 'allOrders' ? null : this.data.selectedProductType
      };

      // 根据当前tab添加骑手筛选
      if (this.data.activeTab === "unclaimedOrders") {
        requestParams.noRiderId = true;
      } else {
        requestParams.riderId = wx.getStorageSync('openId');
      }

      // 添加订单状态筛选
      if (orderStatus) {
        requestParams.orderStatus = orderStatus;
      }

      console.log('调用后端接口，参数:', requestParams);

      const res = await wx.cloud.callFunction({
        name: "xiaoBangCommonFunction",
        data: {
          getOrderListForManageRequest: requestParams
        },
      });
      
      if (res.result.code === 200) {
        let { orders, total } = res.result.data;
        console.log("后端返回订单:", orders);
        console.log("总数:", total);
        
        orders.forEach(order => {
          order.orderType = this.getOrderTypeByProductId(order);
          order.priceText = this.getOrderPriceText(order);
          // 跑腿服务多地址时间信息字段映射
          order.paoTuiPickupAddress = order.pao_tui_pickup_address;
          order.paoTuiPickupTime = order.pao_tui_pickup_time;
          order.paoTuiDeliveryAddress = order.pao_tui_delivery_address;
          order.paoTuiDeliveryTime = order.pao_tui_delivery_time;
          order.paoTuiNote = order.paoTuiNote;
          // 为每个订单添加急件标识
          order.hasUrgentPackage = this.isUrgentOrder(order);
        });

        // 计算急件数量
        const unclaimedUrgentCount = orders.filter(order => 
          !order.deliverOutUserId && this.isUrgentOrder(order)
        ).length;
        const claimedUrgentCount = orders.filter(order => 
          order.deliverOutUserId && this.isUrgentOrder(order)
        ).length;

        // 更新页面数据
        this.setData({
          orders: orders,
          total,
          page: 1, // 重置页码
          unclaimedUrgentCount,
          claimedUrgentCount,
        }, () => {
          this.updateFilteredOrders();
        });
      } else {
        wx.showToast({
          title: res.result.message || "获取订单失败",
          icon: "none",
        });
      }
    } catch (error) {
      console.error("调用云函数失败：", error);
      wx.showToast({
        title: "获取订单失败，请稍后重试",
        icon: "none",
      });
    } finally {
      this.setData({ isLoading: false }); // 重置加载状态
    }
  },

  // 更新筛选后的订单列表
  updateFilteredOrders() {
    const { orders, activeTab, showUrgentOnly, selectedProcessFilterIndex, selectedProductType, selectedStationName } = this.data;
    console.log('updateFilteredOrders 调用，参数:', { activeTab, showUrgentOnly, ordersCount: orders?.length, selectedProcessFilterIndex, selectedProductType, selectedStationName });
    
    // 只在"我领取的订单"里生效；其他 tab 不筛选
    if (activeTab !== 'myOrders') {
      console.log('不在myOrders标签页，不进行筛选');
      // 过滤掉零食代取订单
      const filteredOrders = orders.filter(order => order.orderItem.productId !== 'PSnackPickup');
      this.setData({ filteredOrders: filteredOrders, activeOrders: filteredOrders, completedOrders: [], refundedOrders: [] });
      return;
    }

    let filtered = orders || [];
    console.log('初始订单数量:', filtered.length);
    
    // 产品类型筛选
    if (selectedProductType !== 'allOrders') {
      const beforeProductFilter = filtered.length;
      filtered = filtered.filter(order => order.orderItem.productId === selectedProductType);
      console.log('产品筛选前:', beforeProductFilter, '产品筛选后:', filtered.length);
    }
    
    // 驿站筛选（仅对代取快递生效）
    if (selectedProductType === 'PPacakgePickUp' && selectedStationName !== 'allStations') {
      const beforeStationFilter = filtered.length;
      filtered = filtered.filter(order => {
        // 检查pickupInputs
        if (order.pickupInputs && order.pickupInputs.length > 0) {
          return order.pickupInputs.some(pickup => pickup.stationName === selectedStationName);
        }
        
        // 检查packagePickupInfos
        if (order.packagePickupInfos && order.packagePickupInfos.length > 0) {
          return order.packagePickupInfos.some(pickup => pickup.pickupAddress === selectedStationName);
        }
        
        return false;
      });
      console.log('驿站筛选前:', beforeStationFilter, '驿站筛选后:', filtered.length);
    }
    
    // 只进行急件筛选（状态筛选已由后端完成）
    if (showUrgentOnly) {
      const beforeUrgentFilter = filtered.length;
      filtered = filtered.filter(o => this.isUrgentOrder(o));
      console.log('急件筛选前:', beforeUrgentFilter, '急件筛选后:', filtered.length);
    }
    
    // 为每个订单添加急件标识
    filtered.forEach(order => {
      order.hasUrgentPackage = this.isUrgentOrder(order);
    });
    
    // 根据当前选择的tab设置数据（后端已经筛选过了）
    if (selectedProcessFilterIndex === 0) {
      // 进行中
      console.log('设置进行中订单数据，数量:', filtered.length);
      this.setData({ 
        filteredOrders: filtered, 
        activeOrders: filtered, 
        completedOrders: [],
        refundedOrders: []
      });
    } else if (selectedProcessFilterIndex === 1) {
      // 已完成
      console.log('设置已完成订单数据，数量:', filtered.length);
      this.setData({ 
        filteredOrders: filtered, 
        activeOrders: [], 
        completedOrders: filtered,
        refundedOrders: []
      });
    } else if (selectedProcessFilterIndex === 2) {
      // 已退款
      console.log('设置已退款订单数据，数量:', filtered.length);
      this.setData({ 
        filteredOrders: filtered, 
        activeOrders: [], 
        completedOrders: [],
        refundedOrders: filtered
      });
    }
  },


  // 切换急件过滤
  toggleUrgentFilter(e) {
    console.log('=== 急件过滤切换被触发 ===');
    console.log('事件对象:', e);
    console.log('切换急件过滤，当前状态:', this.data.showUrgentOnly);
    console.log('当前activeTab:', this.data.activeTab);
    
    this.setData({ showUrgentOnly: !this.data.showUrgentOnly }, () => {
      console.log('急件过滤状态已更新为:', this.data.showUrgentOnly);
      this.updateFilteredOrders();
    });
  },

  // 切换订单展开/收起
  toggleOrderExpand(e) {
    const orderId = e.currentTarget.dataset.id;
    const currentMap = this.data.expandedMap || {};
    const userExpandedOrders = this.data.userExpandedOrders || {};
    const willExpand = !currentMap[orderId];
    
    let nextMap = {};
    let nextUserExpandedOrders = { ...userExpandedOrders };
    
    if (willExpand) {
      // 展开当前订单
      nextMap[orderId] = true;
      // 记录用户手动展开的订单
      nextUserExpandedOrders[orderId] = true;
      
      // 保留其他用户手动展开的订单
      Object.keys(userExpandedOrders).forEach(id => {
        if (id !== orderId && userExpandedOrders[id]) {
          nextMap[id] = true;
        }
      });
    } else {
      // 折叠当前订单
      nextMap[orderId] = false;
      // 从用户手动展开列表中移除
      delete nextUserExpandedOrders[orderId];
      
      // 保留其他用户手动展开的订单
      Object.keys(userExpandedOrders).forEach(id => {
        if (id !== orderId && userExpandedOrders[id]) {
          nextMap[id] = true;
        }
      });
    }
    
    this.setData({ 
      expandedMap: nextMap,
      userExpandedOrders: nextUserExpandedOrders
    });
  },
});
